/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GroupBy;

import java.util.*;
import java.util.regex.*;

/**
 *
 * @author Dung Doan
 */
public class GroupBy {
    public GroupBy()
    {
        
    }
    
    public Boolean hasGroupBy(String root)
    {
        String query = root.toUpperCase();
        if (query.indexOf("GROUP BY") < 0)
            return false;
        return true; 
    }
    
    public String getGroupBy(String root)
    {
        String query = root.toUpperCase();
        
        int beginIndex = 0;
        int endIndex = query.indexOf("SELECT");
        if (endIndex < beginIndex)
            return null;
        beginIndex = endIndex + 6;
        
        endIndex = query.indexOf("FROM", beginIndex);
        if (endIndex < beginIndex)
            return null;
        beginIndex = endIndex + 4;
        
        
        endIndex = query.indexOf("WHERE", beginIndex);
        if (endIndex > beginIndex)
            beginIndex = endIndex + 5;
        
        endIndex = query.indexOf("GROUP BY", beginIndex);
        if (endIndex < beginIndex)
            return null;
        
        beginIndex = endIndex + 8;
        
        endIndex = query.indexOf("HAVING", beginIndex);
        if (endIndex > beginIndex)
            return root.substring(beginIndex, endIndex);
        
        endIndex = query.indexOf("ORDER BY");
        if (endIndex > beginIndex)
            return root.substring(beginIndex, endIndex);
        return root.substring(beginIndex);
        
    }
    public List<String> ParseGroupBy(String query)
    {
        ArrayList<String> list = new ArrayList<String>();
        if (hasGroupBy(query) == false) 
            return null;
        String groupByString = getGroupBy(query);
        
        String REGEX = ",";
        
        Pattern p = Pattern.compile(REGEX);
        String[] items = p.split(groupByString);
        
        for (int i = 0 ; i < items.length ; i++)
        {
            list.add(items[i].trim());
        }
        return list;
    }
}
